﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Criterion;
using VictorBlaga.DocumentManagement.Core.Models;
using VictorBlaga.DocumentManagement.Core.Models.Repositories;

namespace VictorBlaga.DocumentManagement.Infrastructure.DataAccess
{
    public class WorkshopRepository : NHibernateRepository, IWorkshopRepository
    {
        public Workshop[] GetAll()
        {
            var query = Session.CreateQuery("from Workshop w orderby w.Name asc");
            return query.List<Workshop>().ToArray();
        }

        public Workshop GetByID(int id)
        {
            var workshop = (Workshop) Session.CreateCriteria(typeof (User)).Add(Expression.Eq("ID", id)).UniqueResult();
            return workshop;
        }

        public void Save(Workshop item)
        {
            Session.Save(item);
        }

        public void Delete(Workshop item)
        {
            Session.Delete(item);
        }

        public bool IsUniqueName(int id, string name)
        {
            var query = Session.CreateQuery("select count(w) from Workshop w where w.Name=:name and ID<>:id");
            query.SetString("name", name.ToLower());
            query.SetInt32("id", id);

            var result = query.UniqueResult();

            return (long)result == 0;
        }
    }
}
